$(function () {
    function UserCreator() {
        // 表格ID
        this.$form = $("#save-form");
        // 按钮
        this.$submit = $('#submit');
        // 初始化
        this.init();
    }

    UserCreator.prototype.Constructor = UserCreator;

    UserCreator.prototype.init = function () {
        this.registEvent();
    };

    UserCreator.prototype.registEvent = function () {
        var that = this;

        $('#username').blur(function () {
            var name = $.trim($('#username').val());
            if (!name) {
                return false;
            }
            SysTool.Ajax.ajaxJsonCall('users/exists', {name: name}, function (b) {
                if (!!b) {
                    $('#username').val('');
                    $('#username').focus();
                    BootBox.warning('用户名已经存在，请重新输入！');
                    return false;
                }
            });
        });

        this.$submit.click(function () {
            var username = $.trim($('#username').val());
            var regex = /^[a-z][a-z0-9]{5,19}$/g;
            if (!username) {
                $('#username').focus();
                BootBox.warning('请输入用户名！');
                return false;
            }
            if (!regex.test(username)) {
                $('#username').focus();
                BootBox.warning('用户名格式不正确！以英文开头，长度为6-20个英文和数字的组合！');
                return false;
            }

            var mobile = $('#mobile').val();
            if (mobile && mobile.length != 11) {
                $('#mobile').focus();
                BootBox.warning('手机号码格式不正确！');
                return false;
            }

            SysTool.Ajax.ajaxJsonCall('users/exists', {name: username}, function (b) {
                if (!!b) {
                    $('#username').val('');
                    $('#username').focus();
                    BootBox.warning('用户名已经存在，请重新输入！');
                    return false;
                }

                SysTool.Ajax.ajaxSubmitForm(that.$form, function (data) {
                    // PopMessage.success('保存成功', function () {
                    window.location.href = "/users/home";
                    // });
                });
            });
        });
    };

    window.UserCreator = new UserCreator();
});